﻿namespace Blaze.Editor.LuaExtensions
{
    using System.Collections.Generic;
    using System.Linq;
    using UnityEditor;

    internal class ChooseScriptDataSource : AdvancedDropdownDataSource
    {
        public ChooseScriptDataSource(ILuaScriptSource scriptSource)
        {
            mScriptSource = scriptSource;
        }

        protected override AdvancedDropdownItem FetchData()
        {
            return RebuildTree();
        }

        protected AdvancedDropdownItem RebuildTree()
        {
            AdvancedDropdownItem root = new ScriptDropdownItem();
            var menuDictionary = mScriptSource.GetMenuItems().ToList();
            menuDictionary.Sort(CompareItems);
            for (var i = 0; i < menuDictionary.Count; i++)
            {
                var menu = menuDictionary[i];
                var menuPath = menu.Key;
                var paths = menuPath.Split('/');

                var parent = root;
                for (var j = 0; j < paths.Length; j++)
                {
                    var path = paths[j];
                    if (j == paths.Length - 1)
                    {
                        var element = new ScriptDropdownItem(path, menuPath, menu.Value);
                        element.searchable = true;
                        element.SetParent(parent);
                        parent.AddChild(element);
                        continue;
                    }

                    var group = parent.children.SingleOrDefault(c => c.name == path);
                    if (group == null)
                    {
                        group = new ScriptDropdownItem(path, -1);
                        group.SetParent(parent);
                        parent.AddChild(group);
                    }

                    parent = group;
                }
            }

            root = root.children.Single();
            root.SetParent(null);
            return root;
        }

        protected override AdvancedDropdownItem Search(string searchString)
        {
            return base.Search(searchString);
        }

        private int CompareItems(KeyValuePair<string, string> x, KeyValuePair<string, string> y)
        {
            return x.Key.CompareTo(y.Key);
        }

        private readonly ILuaScriptSource mScriptSource;
    }
}